// 将来用来存储用户的信息
// 以后咱们自己来实现
import { loginApi, getProfileApi, getUserInfoApi } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'

const state = {
  token: getToken() || '',
  userInfo: {}
}
// this.$store.state.user.token
const mutations = {
  // 存入用户信息
  setUserInfo(state, newUserInfo) {
    state.userInfo = newUserInfo
  },
  // 移除用户信息
  removeUserInfo(state) {
    state.userInfo = {}
  },
  // 存入token
  setToken(state, newToken) {
    state.token = newToken
    setToken(newToken)
  },
  // 移除token
  removeToken(state) {
    // 清空state里的token
    state.token = ''
    // 删除cookie中的token
    removeToken()
  }

}
const getters = {}
const actions = {
  // 登录保存token
  async login(context, data) {
    const res = await loginApi(data)
    const token = res.data
    context.commit('setToken', token)
  },
  // 获取用户基本资料
  async getUserInfo({ commit }) {
    const res = await getProfileApi() // {code:0,data:{},message:""}
    const { data: data1 } = res
    const { data: data2 } = await getUserInfoApi(data1.userId)// {code:0,data:{},message:""}
    const obj = {
      ...data1,
      ...data2
    }
    commit('setUserInfo', obj)
    return res
  },
  // 清除token
  logOut({ commit }) {
    commit('removeUserInfo')
    commit('removeToken')
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  getters,
  actions
}

